import {Component, Input, Output, EventEmitter, OnInit, OnChanges, ChangeDetectorRef} from '@angular/core';
import { NzNotificationService, UploadFile } from 'ng-zorro-antd';
import { Router } from '@angular/router';
import { HttpServcie } from '../../../../service/http.service';
import { Config } from '../../../../service/config';
import { el } from "@angular/platform-browser/testing/src/browser_util";
import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';
import { UserBean } from '../bean/user.bean';
import { FileUploader, FileItem, ParsedResponseHeaders } from 'ng2-file-upload';
import { Observable } from 'rxjs/Rx';
import * as moment from 'moment';


@Component({
  selector: 'user-modify-page',
  templateUrl: 'user-modify.html',
  styleUrls: ['user-modify.scss']
})
export class UserModifyPage implements OnInit, OnChanges {
  validateForm: FormGroup;
  isSpinning: boolean = false;
  functions: any = [];
  @Input() inValue: any = [];
  @Output("outPut") outPut = new EventEmitter();
  config: any = Config;
  //系统类型
  personalBean: UserBean = new UserBean();
  roleTypeList = [];
  _useroptions = [];  //角色类型
  _cardTypeoption = [];
  partyList = [];
  cardType: any = [];
  user: any = {};
  showPS = false;

  // 社保证明回显
  public socialList=[];
  public photoLists :any= [];

  constructor(
    private fb: FormBuilder,
    private httpServcie: HttpServcie,
    private _notification: NzNotificationService,
    public cd: ChangeDetectorRef,
  ) {
  }

  ngOnInit() {
    this.validateForm = this.fb.group({
      userName: [null, [Validators.required]],//用户姓名
      cardType: [null, [Validators.nullValidator]],//用户持证类型
      cardTypeNumber: [null, [Validators.nullValidator]],//证件号
      cardNumber: [null, [Validators.required,this.cardNumberCheck]],//身份证号码
      partyId: [null, [Validators.required]],//单位全称
      mobile: [null, [Validators.nullValidator]],//办公电话
      email: [null, [Validators.nullValidator]],//E-mail
      agree: [null, [Validators.nullValidator]],
      // roleTypeId: [null, [Validators.nullValidator]],//角色所属类型
      roleId: [null, [Validators.nullValidator]],//角色
      phone: [null, [Validators.required, this.mobileCheck]],
      firstgtshow: [null, [Validators.nullValidator]],
    });
    this.user = JSON.parse(window.localStorage.getItem("user"));
    this.personalBean.type = "user";

    //查询单位全称
    if(this.user){
      let userList=[];
      userList.push(this.user);
      this.partyList = userList;
      if(this.user.partyId) {
        this.personalBean.partyId = this.user.partyId;
      }
    }
    if (this.user.partyId) {
      this.personalBean.partyId = this.user.partyId;
      //查询机构下的角色类型
      this.httpServcie.registRoleTypeList(this.user.partyId).subscribe(data => {
        if (data.status == '200') {
          this.httpServcie.registerRoleList(this.user.partyType).subscribe(data => {
            if (data.status == '200') {
              this._useroptions = data.data;
              this.personalBean.roleId = this.personalBean.roleId;
            }
          })
        } else {
          this.roleAll();
        }
      })
    } else {
      //查询机的所有角色
      this._useroptions = [{roleName: '请选择', id: ''}];
      this.personalBean.roleId = '';
    }
    this.showPS = this.user.partyType == "4";
    if (this.showPS) {
      this.validateForm = this.fb.group({
        userName: [null, [Validators.required, this.userNameCheck]],//用户姓名
        password: [null, [Validators.required]],
        checkPassword: [null, [Validators.required, this.confirmationValidator]],
        userCode: [null, [Validators.required]], //用户名
        cardType: [null, [Validators.nullValidator]],//用户持证类型
        cardTypeNumber: [null, [Validators.nullValidator]],//证件号
        cardNumber: [null, [Validators.required,this.cardNumberCheck]],//身份证号码
        workNumber: [null, [Validators.required]],//工号
        partyId: [null, [Validators.required]],//单位全称
        mobile: [null, [Validators.nullValidator]],//办公电话
        email: [null, [Validators.nullValidator]],//E-mail
        agree: [null, [Validators.nullValidator]],
        // roleTypeId: [null, [Validators.nullValidator]],//角色所属类型
        roleId: [null, [Validators.required]],//角色
        phone: [null, [Validators.required, this.mobileCheck]],
        firstgtshow: [null, [Validators.nullValidator]],
      });
      this.validateForm.controls["checkPassword"].setValue(this.personalBean.password);

      this.personalBean.roleTypeId = '2';
      this._cardTypeoption = [
        { value: '', label: '请选择' },
        { value: '监察A类', label: '监察A类' },
        { value: '监察B类', label: '监察B类' },
        { value: '监管协管员证', label: '监管协管员证' },
        { value: '其他', label: '其他' },
      ];
    }
    this.httpServcie.registerRoleList(this.user.partyType).subscribe(data => {
      if (data.status == '200') {
        this._useroptions = data.data;
      }
    });

  }

  ngOnChanges() {
    this._cardTypeoption = [
      { value: '', label: '请选择' },
      { value: 'A1', label: 'A1' },
      { value: 'A2', label: 'A2' },
      { value: 'A4', label: 'A4' },
      { value: 'T', label: 'T' },
      { value: 'T1', label: 'T1' },
      { value: 'T2', label: 'T2' },
      { value: 'T3', label: 'T3' },
      { value: '监察A类', label: '监察A类' },
      { value: '监察B类', label: '监察B类' },
      { value: '其他', label: '其他' },
    ];
    if (this.showPS) {
      this._cardTypeoption = [
        { value: '', label: '请选择' },
        { value: '监察A类', label: '监察A类' },
        { value: '监察B类', label: '监察B类' },
        { value: '监管协管员证', label: '监管协管员证' },
        { value: '其他', label: '其他' },
      ];
    }
    if (this.inValue) {
      this.personalBean = Object.assign({}, this.inValue);

      if (this.personalBean.cardType) {
        this.cardType = this.personalBean.cardType.split(",");
      }
      if (this.personalBean.firstgt) {
        this.personalBean.firstgtshow = new Date(moment(this.personalBean.firstgt).format('YYYY-MM-DD'));
      }
      //图片回显
      if (this.personalBean.fileList) {
        let list = this.personalBean.fileList.split(",");
        let addList: any = [];
        list.forEach((element, index) => {
          let up: any = {};
          up['uid'] = index + '';
          up['url'] = this.config.IP + this.config.API.getUpload + "/" + element;
          up['thumbUrl'] = this.config.IP + this.config.API.getUpload + "/" + element;
          up['response'] = { data: element };
          addList.push(up)
        })
        this.fileList = addList;
      }
      // 社保照片回显
      if (this.personalBean.socialList) {
        let list = this.personalBean.socialList.split(",");
        let addList: any = [];

        list.forEach((element, index) => {
          if(element !=null && element !=""){
            let uid = new Date();
            addList.push({
              uid: uid.getTime(),
              name: element,
              status: "done",
              url: `${this.config.IP + this.config.API.getUpload}${element}`
            });
          }
        })
        this.socialList = addList;
      }
      if(this.personalBean.signImg) {
        let list = this.personalBean.signImg.split(",");
        let addList: any = [];
        list.forEach((element, index) => {
          let up: any = {};
          up['uid'] = index + '';
          up['url'] = this.config.IP + this.config.API.getUpload + "/" + element;
          up['thumbUrl'] = this.config.IP + this.config.API.getUpload + "/" + element;
          up['response'] = { data: element };
          addList.push(up)
        })
        this.signImg = addList;
      }
    }

  }
  ChangType() {
    if (this.personalBean.roleId == '7') {
      this._cardTypeoption = [
        { value: "T", label: "T" },
        { value: "T1", label: "T1" },
        { value: "T2", label: "T2" }
      ];
    }
    if (this.personalBean.roleId == '5' || this.personalBean.roleId == '6') {
      this._cardTypeoption = [
        { value: "A4", label: "A4" },
        { value: "其他", label: "其他" }
      ];
    }
    if ( this.personalBean.roleId == '6') {
      this._cardTypeoption = [
        { value: "T3", label: "T3" },
        { value: "其他", label: "其他" }
      ];
    }
    if (this.personalBean.roleId == '3'
      || this.personalBean.roleId == '4'
      || this.personalBean.roleId == '18') {
      this._cardTypeoption = [
        { value: "监察A类", label: "监察A类" },
        { value: "监察B类", label: "监察B类" },
        { value: "监察协管员证", label: "监察协管员证" },
        { value: "其他", label: "其他" }
      ];
    }
    if (this.personalBean.roleId == '16') {
      this._cardTypeoption = [
        { value: "A1", label: "A1" },
        { value: "A2", label: "A2" },
        { value: "A4", label: "A4" },
        { value: "T3", label: "T3" },
        { value: "其他", label: "其他" }
      ];
    }

    if (this.personalBean.roleId == '17'){
      this._cardTypeoption = [
        { value: "T", label: "T" },
        { value: "T1", label: "T1" },
        { value: "T2", label: "T2" },
        { value: "其他", label: "其他" }
      ];
    }

    if (this.personalBean.roleId == '8') {
      this._cardTypeoption = [
        { value: "电梯检验员证", label: "电梯检验员证" },
        { value: "电梯检验师证", label: "电梯检验师证" }
      ];
    }
    if (this.personalBean.roleId == '19') {
      this._cardTypeoption = [
        { value: "电梯检验员证", label: "电梯检验员证" },
        { value: "电梯检验师证", label: "电梯检验师证" },
        { value: "其他", label: "其他" }
      ];
    }
  }
  submitForm($event) {
    //校验是否能提交
    //没有填的标红
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
    }
    //处理是否提交
    for (const i in this.validateForm.controls) {
      if (!this.validateForm.controls[i].valid) {
        return;
      }
    }
    this.isSpinning = true;

    for (let role of this._useroptions) {
      if (this.personalBean.roleId == role.roleId) {
        this.personalBean.roleName = role.roleName;
        break;
      }
    }
    //附件
    let tempFileList = [];
    if (this.fileList.length > 0) {
      this.fileList.forEach(element => {
        tempFileList.push(element['response']['data']);
      });
      this.personalBean.fileList = tempFileList.join(",");
    }else{
      this.personalBean.fileList = "";
    }

    // 社保证明附件
    // 修改照片
    let photo = "";
    if (this.socialList != null && this.socialList.length) {
      for (let i = 0; i < this.socialList.length; i++) {

        if (this.socialList[i].status == "done") {
          // 回调的图片处理
          if (this.socialList[i]["url"]) {
            let url = `${this.socialList[i].name}`;
            photo += url + ",";
          } else {
            let url = `${this.socialList[i]["response"].data}`;
            photo += url + ",";
          }
          // 上传的图片处理
        }
      }

    }
    this.personalBean.socialList = photo;


    // 初次取证时间
    if(this.personalBean.firstgt != null && this.personalBean.firstgt != ""){
      this.personalBean.firstgt = moment(this.personalBean.firstgt).format('YYYYMMDD');
    }
    if (this.cardType) {
      this.personalBean.cardType = this.cardType.toString();
    }
    if(this.signImg.length){
      let ret = Object.assign([],this.signImg);
      this.personalBean.signImg = ret[0]["response"]["data"];
    }else{
      this.personalBean.signImg = "";
    }
    let ob = this.httpServcie.updateUser(this.personalBean);
    ob.subscribe((data) => {
      this.isSpinning = false;
      if (data.status == 200) {
        this._notification.create('success', '成功提示', '修改成功');
        this.outPut.emit($event);
      } else {
        this._notification.create('error', '失败提示', data.message);
        return;
      }
    })

  }

  //用户姓名校验
  userNameCheck = (control: FormControl): { [s: string]: boolean } => {
    if (!control.value) {
      return {required: true};
    }else if (control.value){
      let reg =/^[\u4e00-\u9fa5]{2,5}$/;
      if (!reg.test(control.value)) {
        return { checkFormat: true, error: true };
      }
    }
  }

  // 身份证号码校验
  cardNumberCheck = (control: FormControl): { [s: string]: boolean } => {
    if (!control.value) {
      return { required: true };
    } else if (control.value) {
      let reg = /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
      if (!reg.test(control.value)) {
        return { checkFormat: true, error: true };
      }
    }
  };

  //手机号码校验
  mobileCheck = (control: FormControl): { [s: string]: boolean } => {
    if (!control.value) {
      return { required: true };
    } else if (control.value) {
      let reg = /^1[0-9]{10}$/;
      if (!reg.test(control.value)) {
        return { checkMobile: true, error: true };
      }
    }
  };
  confirmationValidator = (control: FormControl): { [s: string]: boolean } => {
    if (!control.value) {
      return { required: true };
    } else if (control.value !== this.validateForm.controls["password"].value) {
      return { confirm: true, error: true };
    }
  };

  updateConfirmValidator() {
    /** wait for refresh value */
    setTimeout(_ => {
      this.validateForm.controls["checkPassword"].updateValueAndValidity();
    });
  }

  //交验
  getFormControl(name) {
    return this.validateForm.controls[name];
  }

  //选择单位
  partyListChange() {
    if (this.personalBean.partyId) {
      this.httpServcie.registRoleTypeList(this.user.partyId).subscribe(data => {
        if (data.status == '200') {
          this.roleTypeList = data.data;
        }
      })
    } else {
      this.roleTypeList = [{ roleTypeName: '请选择', id: '' }];
      this.personalBean.roleTypeId = '';
      this.roleTypeChange();
    }
  }
  //选择角色类型
  roleTypeChange() {
    if (this.personalBean.roleTypeId) {
      this.httpServcie.registerRoleList(this.user.partyType).subscribe(data => {
        if (data.status == '200') {
          this._useroptions = data.data;
        }
      })
    } else {
      //查询机构下的所有角色
      this._useroptions = [{ roleName: '请选择', id: '' }];
      this.personalBean.roleId = '';
    }
  }

  //查询出所有的角色
  roleAll() {
    this.httpServcie.queryByPartyTypeList(this.user.partyType).subscribe(data => {
      if (data.status == '200') {
        this._useroptions = data.data;
        if (this.personalBean.roleId) {
          this.personalBean.roleId = this.personalBean.roleId;
        }
      }
    })
  }


  //文件上传
  previewImage = '';
  previewVisible = false;
  fileList: UploadFile[] = [];
  signImg : UploadFile[] = [];

  handlePreview = (file: UploadFile) => {
    this.previewImage = file.url || file.thumbUrl;
    this.previewVisible = true;
  };

  /**
   * 上传就开始调用
   * @param info
   */
  handleChange(event) {
    if (event.file.status == "error") {
      this._notification.blank("上传失败", `${event.file.message}`);
    }
    this.cd.detectChanges();
  }

  //移除文件
  nzRemoveFile = (file: UploadFile) => {
    //移除fileList中的数据
    if (this.fileList.length == 1) {
      this.fileList = [];
      return;
    }
    let list: UploadFile[] = [];
    this.fileList.forEach((element, index) => {
      if (element['thumbUrl'] == file.thumbUrl) {
        this.fileList.splice(index, 1);
        this.fileList = this.fileList;
        list = this.fileList;
        this.fileList = [];
      }
    });
    list.forEach(element => {
      this.fileList.push(element);
    })
  }

  //移除文件
  nzRemoveFile1 = (file: UploadFile) => {
    //移除fileList中的数据
    if (this.signImg.length == 1) {
      this.signImg = [];
      return;
    }
  }


  //移除社保证明文件
  nzSocialRemoveFile = (file: UploadFile) => {
    let fileItem = file;
    if (fileItem["status"] == "removed") {
      if (fileItem["url"] && fileItem["url"].includes("http")) {
        this.deleteImg(fileItem.name);
      } else {
        this.deleteImg(fileItem["response"]["data"]);
      }
    }
  };

  // 删除图片服务
  deleteImg(filedata) {
    this.httpServcie.deleteUpload(filedata).subscribe(
      data => {
        if (data["status"] != "200") {
          this._notification.create("error", "错误提示", data.message);
          return;
        }
        if(data["status"] == "200"){
          this._notification.create("success", "成功提示", "删除成功，请点击修改按钮，进行数据保存！");
        }else{
          this._notification.create("error", "错误提示", data.message);
        }
        this.socialList.forEach((element, index) => {
          console.log(element);
          if (element["status"] == "removed") {
            this.socialList.splice(index, 1);
            this.photoLists = this.socialList;

            this.socialList = this.photoLists;

          }
        });
      },
      error => {
        this._notification.create("error", "错误提示", "请求超时！");
        return;
      }
    );
  }

  /**
   * 社保上传就开始调用
   * @param info
   */
  socialHandleChange(info: { file: UploadFile }) {
    if (info.file.status === "uploading") {
      return;
    }
    if (info.file.status === "done") {
      this.photoLists = this.socialList;
    }
  }


}
